import { call, fork, put, take, throttle, takeLatest, cancelled } from 'redux-saga/effects';
import { Navigation } from 'react-native-navigation';
import types from './types';
import userTypes from '../user/types';
import userAction from '../user/actions';
import { Toast } from 'antd-mobile-rn';
import { getSign, getSignForCode } from '../../service/user/index';
import Storage from '../../utils/storage';
import AnalyticsUtil from '../../utils/umeng/AnalyticsUtil';

let Sagas = {};

/**
 * 发起登录流
 */
Sagas['loginFlow'] = function* () {
  while (true) {
    // 发起登录请求
    const payload = yield take(types.Login_Request);
    // 发起登录流任务
    const task = yield fork(authorize, payload);
  }
};

// 用户认证模块
function* authorize(payload) {
  try {
    // 登录
    yield put({ type: types.Loading_Start });  // 开始loading状态
    const data = yield call(getSignForCode, payload);
    console.log('authorize', data.data.token);
    yield put({ type: types.Login_Success, data: data });
  } catch (e) {
    yield put({ type: types.Login_Error, e }); // 登录异常
  } finally {
    if (yield cancelled()) {
      console.log('cancelled');
    }
    yield put({ type: types.Loading_End });  // 结束loading状态
  }
}

// 登录状态接收
Sagas['loginStatus'] = function* () {
  while (true) {
    // 登录成功
    let { data } = yield take(types.Login_Success);
    if (data && data.code === 0) {
      Toast.success('登录成功');
      Storage.save('token', data.data.token);
      Navigation.dismissModal();
      // 更新用户信息
      yield put({ type: userTypes.GetUserInfo, payload: { token: data.data.token }});
    } else {
      yield put({ type: types.Login_Error, data });
    }
  }
};

// 退出登录操作
Sagas['logout'] = function* () {
  while (true) {
    yield take(types.Logout);
    Storage.clearall();
    yield put(userAction.Clear());
  }
};

// loading状态
Sagas['loadingStatus'] = function* () {
  while (true) {
    yield take(types.Loading_Start, loadingStart);
    yield put({ type: types.RenderData, payload: { loading: true }});

    yield take(types.Loading_End, loadingEnd);
    yield put({ type: types.RenderData, payload: { loading: false }});
  }
};

function* loadingStart() {
  yield put({ type: types.RenderData, payload: { loading: true }});
}

function* loadingEnd() {
  yield put({ type: types.RenderData, payload: { loading: false }});
}

export default Sagas;
